package com.saodisheng.service.impl;

import com.jfinal.kit.Ret;
import com.saodisheng.service.AdminDbService;
import com.saodisheng.constant.AttributeConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 * description:
 *
 * @author 扫地生_saodisheng
 * @date 2022/1/29
 */
@Service
@Slf4j
public class AdminDbServiceImpl implements AdminDbService {
    @Override
    public boolean exportDatabaseTool(String hostIP, String userName, String password, String savePath, String fileName, String databaseName) {
        File saveFile = new File(savePath);
        // 如果目录不存在
        if (!saveFile.exists()) {
            // 创建文件夹
            saveFile.mkdirs();
        }  
        if(!savePath.endsWith(File.separator)){  
            savePath = savePath + File.separator;  
        }  
          
        PrintWriter printWriter = null;  
        BufferedReader bufferedReader = null;  
        try {  
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));  
            Process process = Runtime.getRuntime().exec(AttributeConstant.mysqlPath+"mysqldump -h" + hostIP +" -p3306" + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName);
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");  
            bufferedReader = new BufferedReader(inputStreamReader);  
            String line;  
            while((line = bufferedReader.readLine())!= null){  
                printWriter.println(line);  
            }  
            printWriter.flush();
            //0 表示线程正常终止。
            if(process.waitFor() == 0){
                return true;  
            }  
        }catch (IOException | InterruptedException e) {
            e.printStackTrace();  
        } finally {  
            try {  
                if (bufferedReader != null) {  
                    bufferedReader.close();  
                }  
                if (printWriter != null) {  
                    printWriter.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return false;  
    }  
    
    @Override
    public Ret restore(String restoreFile, String dbName){
    	 String mysql = AttributeConstant.mysqlPath + "mysql " + "-h" + AttributeConstant.WEBIP + " -u"
                 + AttributeConstant.mysqlUser + " -p" + AttributeConstant.mysqlPassword + " " + dbName + " < " + restoreFile;
         log.info("+++++++++++++++++++++++++++" + mysql);
        try {
            Runtime.getRuntime().exec("cmd /c " + mysql);
            System.out.println("还原成功!");
            return Ret.ok("msg", "还原数据库成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Ret.fail("msg", "还原数据库失败");
	}
}
